package cn.broadsense.biz.handler;

import cn.broadsense.common.utils.StringUtils;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author huangjinshi
 * @description
 * @createDate 2023-09-13 10:56:21
 */
@Slf4j
@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes(List.class)
public class ListHandler implements TypeHandler<List<String>> {

    @Override
    public void setParameter(PreparedStatement ps, int i, List<String> parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, JSONObject.toJSONString(parameter));
    }

    @Override
    public List<String> getResult(ResultSet resultSet, String s) throws SQLException {
        String result = resultSet.getString(s);
        List<String> list = new ArrayList<>();
        if (StringUtils.isNotBlank(result)) {
            list = JSONObject.parseObject(result, new TypeReference<List<String>>() {
            });
        }
        return list;
    }

    @Override
    public List<String> getResult(ResultSet resultSet, int i) throws SQLException {
        String result = resultSet.getString(i);
        List<String> list = new ArrayList<>();
        if (StringUtils.isNotBlank(result)) {
            list = JSONObject.parseObject(result, new TypeReference<List<String>>() {
            });
        }
        return list;
    }

    @Override
    public List<String> getResult(CallableStatement callableStatement, int i) throws SQLException {
        String result = callableStatement.getString(i);
        List<String> list = new ArrayList<>();
        if (StringUtils.isNotBlank(result)) {
            list = JSONObject.parseObject(result, new TypeReference<List<String>>() {
            });
        }
        return list;
    }
}
